<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Wants {
	private $_mimes = array();
	
	function Wants()
	{
		// load mime types file; have to do it here because of some weirdness using global... odd.
		include(APPPATH.'config/mimes'.EXT);
		$this->_mimes = $mimes;
	}
	
	// handles method calls such as $this->wants->xml()
	// returns a boolean indicating whether the current request's mime-type is the same as the mime-type passed in (the method name)
	// this method uses CI's $mimes array, as it's rather robust and makes sense to use vs. rolling our own
	//
	// examples:
	// $this->wants->js()
	// $this->wants->html()
	function __call($m, $a)
	{
		$mimes = $this->_mimes;
		
		log_message('debug', "Wants::__call() with $m MIME={$mimes[$m]} CT=".$this->_content_type());
		
		if (isset($mimes[$m]))
		{
			if (is_array($mimes[$m]))
			{
				if (in_array($mimes[$m], $this->_content_type()))
				{
					// request content-type matches the desired mime-type, so return true
					log_message('debug', "wants->$m TRUE");
					return true;
				}
			}
			else
			{
				if ($this->_content_type() == $mimes[$m])
				{
					// request content-type matches the desired mime-type, so return true
					log_message('debug', "wants->$m TRUE");
					return true;
				}
			}
		}
	}
	
	private function _content_type()
	{
		// if a file extension is present in the url, force the content-type to that mime-type;
		// this is *very* rudimentary at best, hc svnt dracones!
		if (preg_match('/\.(.*)/', $_SERVER['QUERY_STRING'], $matches))
		{
			$mimes		= $this->_mimes;
			$mime_type 	= $mimes[$matches[1]];
			return $mime_type;
		}
		else
			return (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : 'text/html'; // is there a better default?
	}
}
?>